package com.why.blog.config.exception;

import com.why.blog.common.BusinessRuntimeException;
import com.why.blog.common.R;
import com.why.blog.common.ResponseCode;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * description: 全局异常解析器
 *
 * @author: taohan
 * @date: 2019年04月16日
 * @time: 9:22
 */
@ControllerAdvice
public class GlobalExceptionResolver {
	

	/**
	 * 处理系统所有未知异常
	 * @param e 异常
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public R handleException(Exception e) {
		return R.getInstance(ResponseCode.SYSTEM_ERROR.getCode(), "系统未知异常");
	}

	/**
	 * 处理所有业务异常
	 *
	 * @param e 业务异常
	 * @return
	 */
	@ExceptionHandler(BusinessRuntimeException.class)
	@ResponseBody
	public R handleOpdRuntimeException(BusinessRuntimeException e) {
		return R.getInstance(e.getCode(), e.getMsg());
	}

	/**
	 * 处理所有请求方式异常
	 *
	 * @param e 请求方式异常
	 * @return
	 */
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	@ResponseBody
	public R handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
		return R.getInstance("404", "您的请求方式 [" + e.getMethod() + "] 不支持");
	}


	/**
	 * 处理所有请求参数错误异常
	 *
	 * @param e Exception
	 * @return
	 */
	@ExceptionHandler(MissingServletRequestParameterException.class)
	@ResponseBody
	public R handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
		return R.getInstance(ResponseCode.ARG_ERROR.getCode(), "缺失必要的请求参数 [" + e.getParameterName() + "]");
	}
}
